package com.cskaoyan.shiro;

import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

/**
 * @author heyyon
 */
@Configuration
public class ShiroConfig {
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager webSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //认证失败后返回的url

        shiroFilterFactoryBean.setSecurityManager(webSecurityManager);
        LinkedHashMap<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/admin/auth/login", "anon");
        filterMap.put("/admin/auth/unAuthc", "anon");

        filterMap.put("/templates/index.ftlh", "anon");
        filterMap.put("/wx/auth/login", "anon");//微信程序的登录和首页,首页商品，不需要权限
        filterMap.put("/wx/home/index", "anon");
        filterMap.put("/wx/goods/count", "anon");
        filterMap.put("/wx/storage/upload", "anon");
        filterMap.put("/wx/search/**", "anon");
        filterMap.put("/wx/search/index", "anon");
        filterMap.put("wx/goods/**", "anon");
        filterMap.put("/wx/goods/*", "anon");
        filterMap.put("/admin/**", "authc");
        filterMap.put("/wx/**", "authc");
//        filterMap.put("/templates/index.ftlh", "anon");
//        filterMap.put("/**", "authc");
        filterMap.put("/upload/**", "anon");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return shiroFilterFactoryBean;
    }

    @Bean
    public DefaultWebSecurityManager securityManager(CustomRealm customRealm, DefaultWebSessionManager webSessionManager) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(customRealm);
        defaultWebSecurityManager.setSessionManager(webSessionManager);
        return defaultWebSecurityManager;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager defaultWebSecurityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(defaultWebSecurityManager);
        return authorizationAttributeSourceAdvisor;
    }

    @Bean
    public DefaultWebSessionManager webSessionManager() {
        CustomSessionManager customSessionManager = new CustomSessionManager();
        return customSessionManager;
    }
}
